//
//  BKClassifyViewController.m
//  bestkeep
//
//  Created by 武探 on 2016/11/3.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKClassifyViewController.h"
#import "BKTreeDataModel.h"
#import "BKClasssifyLeftTableViewCell.h"
#import "BKRightCollectionViewCell.h"
#import "masonry.h"
#import "BKClassifyLeftTable.h"
#import "BKRightCollectionView.h"
#import "BKClassifyCommon.h"
#import "SystemMessageVC.h"
#import "Mediator+BKSearch.h"
#import "Mediator+BKClassify.h"
#import "Mediator+BKMy.h"

static NSString *LeftIdentifier = @"BKClasssifyLeftTableViewCell";
static NSString *RightIdentifier = @"BKRightCollectionViewCell";

#define tableWidthSize 210.0f/750.0f*ScreenWidth //表格的宽度
#define tableCellHeight 10.0f/21.0f*tableWidthSize //行的高度

@interface BKClassifyViewController ()<BKClassifyLeftTableDelegate, BKClassifyRightDelegate>

@property (nonatomic, strong) BKClassifyLeftTable *leftTableView; //左边的列表
@property (nonatomic, strong) NSMutableArray *leftDataArray; //左边列表的数据源
@property (nonatomic, strong) NSMutableArray *rightdataArray; //右边列表的过滤数据源
@property (nonatomic, strong) NSMutableArray *allRightdataArray; //右边列表数据源
@property (nonatomic, strong) BKRightCollectionView *rightCollectionView; //右边列表
@property (nonatomic, strong) BKTreeDataModel *treeDataModel; //当前被选中的ID值
@property (nonatomic, strong) FirstChildrenList *currentSelectModel; //当前选择的模型
@property (nonatomic, strong) NSMutableDictionary *classifyDic; //将总的分类作为key，细的分类作为value
@property (nonatomic, assign) NSInteger seletedIndex;
@property (nonatomic, strong) UIView *upLoadView;
@property (nonatomic, strong) ExceptionView *exceptionView; //错误提示页面
@property (nonatomic, strong) UIView *badgeView; //消息红点
@property (nonatomic, strong) NSMutableArray *arr;
@end

@implementation BKClassifyViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [BKClassifyCommon haveNewInformation:self.badgeView];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self setupNavigation];
    [self getCategoryTreeList];
    
    _arr = [NSMutableArray arrayWithObjects:@"0", nil];
}

-(void)setupNavigation{
    [self createItem];
    [self createSeachView];
}

-(void)createItem{
    //左Logo
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.userInteractionEnabled = NO;
    leftBtn.frame = CGRectMake(0, 0, 30, 28);
    [leftBtn setImage:[UIImage imageNamed:@"top_logo_"] forState:UIControlStateNormal];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    space.width = -4;
    self.navigationItem.leftBarButtonItems = @[space, leftItem];
    //右消息
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 28, 23);
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"消息中心icon"]];
    imageView.frame = CGRectMake(5, 0, 23, 23);
    self.badgeView = [[UIView alloc]initWithFrame:CGRectMake(17, 0, 6, 6)];
    self.badgeView.layer.cornerRadius = 3;
    self.badgeView.layer.masksToBounds = YES;
    self.badgeView.backgroundColor = [UIColor redColor];
    [imageView addSubview:self.badgeView];
    [rightBtn addSubview:imageView];
    [rightBtn addTarget:self action:@selector(infoAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

-(void)createSeachView{
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 98, 30)];
    titleView.layer.cornerRadius = 15;//3;
    titleView.layer.masksToBounds = YES;
    [titleView setBackgroundColor:[UIColor clearColor]];
    
    UIView *searchBarView = [[UIView alloc]initWithFrame:CGRectMake(4, 0, ScreenWidth-86, 30)];
    searchBarView.backgroundColor = RGBACOLOR(218, 218, 218, 0.5);
    searchBarView.layer.masksToBounds = YES;
    searchBarView.layer.cornerRadius = 15;
    [titleView addSubview: searchBarView];
    
    UITextField * searchTextField = [[UITextField alloc]initWithFrame:titleView.bounds];
    searchTextField.backgroundColor = [UIColor clearColor];//[UIColor colorWithRed:(218/255.0) green:(218/255.0) blue:(218/255.0) alpha:0.5];
    searchTextField.font = [UIFont systemFontOfSize:14];
    
    searchTextField.placeholder = @"  请输入商品名称";
    [searchTextField setValue:RGB(178, 178, 178) forKeyPath:@"_placeholderLabel.textColor"];
    searchTextField.textAlignment = NSTextAlignmentCenter;
    [searchBarView addSubview:searchTextField];
    UIImageView * imgV = [[UIImageView alloc]init];
    imgV.frame = CGRectMake(searchTextField.frame.size.width/2-10-[self sizeWithContentString:searchTextField.placeholder textFont:[UIFont systemFontOfSize:14] size:CGSizeMake(1000, 15)].width/2,8, 14, 14);
    imgV.image = [UIImage imageNamed:@"searchIcon"];
    [titleView addSubview:imgV];
    UIControl *gotoSeaarchControl = [[UIControl alloc] initWithFrame:searchTextField.bounds];
    [gotoSeaarchControl addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    [searchTextField addSubview:gotoSeaarchControl];
    self.navigationItem.titleView = titleView;
}

-(CGSize)sizeWithContentString:(NSString *)content textFont:(UIFont *)font size:(CGSize)contentSize{
    
    NSDictionary * fontDict = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    CGRect rect = [content boundingRectWithSize:contentSize options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDict context:nil];
    
    return rect.size;
}


-(void)searchAction{
    UIViewController *search = [[Mediator sharedInstance]BKSearchViewController];
    search.navigationItem.hidesBackButton = YES;
    [self.navigationController pushViewController:search animated:NO];
}

-(void)infoAction{
    NSDictionary *dict = [[Mediator sharedInstance] BKMyUserInfo];
    NSNumber *logIn = dict[@"BKMyUserIsLoginKey"];
    if ([logIn isEqualToNumber:@1]) {
        SystemMessageVC *system = [[SystemMessageVC alloc]init];
        [self.navigationController pushViewController:system animated:YES];
    } else {
        [[Mediator sharedInstance] userGoToLoginFromOrignalController:self finishBlock:^{
        }];
    }
}
//创建左右视图
-(void)createUI{
    self.view.backgroundColor = [UIColor whiteColor];
    //左边一级菜单
    if (!_leftTableView) {
        _leftTableView = [[BKClassifyLeftTable alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _leftTableView.leftTableDelegate = self;
        [self.view addSubview:_leftTableView];
        [_leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top);
            make.left.equalTo(self.view.mas_left);
            make.width.equalTo(self.view.mas_width).multipliedBy(0.28);
            make.bottom.equalTo(self.view.mas_bottom).offset(-49);
        }];
    }
    //右边二级菜单
   if (!_rightCollectionView) {
       UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        _rightCollectionView = [[BKRightCollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        _rightCollectionView.classifyRightDelegate = self;
        [self.view addSubview:_rightCollectionView];
        [self.rightCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top);
            make.left.equalTo(_leftTableView.mas_right);
            make.right.equalTo(self.view.mas_right);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
}

#pragma mark -- 加载数据的方法
-(void)getCategoryTreeList{
    
    [LoadingView loadingShoppingCartInView:self.view];
    [BKClassifyCommon getGoodsClassifyTreeInfo:nil compeletion:^(id result, NSError *error) {
       if(self.exceptionView) {
           [self.exceptionView dismiss];
           self.exceptionView = nil;
       }
       if (result) {
           [self createUI];
           self.treeDataModel = result;
           for (FirstChildrenList *firstChild in self.treeDataModel.list) {
               [_leftDataArray addObject:firstChild];
               self.leftTableView.leftTableArray = self.leftDataArray;
               NSMutableArray *tempArray = [NSMutableArray array];//获取一个小分区的数据
               for (SecondChildrenList *secondChild in firstChild.childrenList){
                   [tempArray addObject:secondChild];
                   [self.classifyDic setObject:tempArray forKey:firstChild.name];
               }
           }
           
           self.currentSelectModel = [self.leftDataArray objectAtIndex:0];
           self.leftTableView.currentSelectModel = self.currentSelectModel;
           NSString *key = self.currentSelectModel.name;
           NSArray *thirdModel = [self.classifyDic objectForKey:key];
           //更新collection的数据
           [self UpdateRightData:thirdModel];
           [self.rightCollectionView reloadData];
           [self.leftTableView reloadData];
           
        }
        if (self.treeDataModel.list.count == 0) {
            
            ExceptionCodeType type = ExceptionCodeTypeNoNetwork;
            type = ExceptionCodeTypeEmptyPages;
            self.exceptionView = [ExceptionView exceptionViewWithType:type];
            self.exceptionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
            ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:type handler:^(ExceptionViewAction *action) {
                [_exceptionView dismiss];
                _exceptionView = nil;
                [self getCategoryTreeList];
            }];
            [self.exceptionView addAction:retryAction];
            [self.exceptionView showInView:self.view];
                self.exceptionView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height+64);
        }
        [LoadingView dismiss];
   } failure:^(id result, NSError *error) {
       if(!self.exceptionView && error) {
           ExceptionCodeType type = ExceptionCodeTypeNoNetwork;
           if (error.code == -1009) {
               type = ExceptionCodeTypeNoNetwork;
           }else if (error.code == -1001){
               type = ExceptionCodeTypeRequestFailed;
           }else if (error.code == 502 || error.code == 404){
               type = ExceptionCodeTypeServerError;
           }else{
               type = ExceptionCodeTypeFailedToLoad;
           }
           self.exceptionView = [ExceptionView exceptionViewWithType:type];
           self.exceptionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
           ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:type handler:^(ExceptionViewAction *action) {
               [_exceptionView dismiss];
               _exceptionView = nil;
               [self getCategoryTreeList];
           }];
           [self.exceptionView addAction:retryAction];
           [self.exceptionView showInView:self.view];
           self.exceptionView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height+64);
       }
       [LoadingView dismiss];
   }];
    
    self.seletedIndex = 0;
    if (self.leftDataArray.count > 0) {
        //设置当前选择的model
        self.currentSelectModel = [self.leftDataArray objectAtIndex:self.seletedIndex];
        self.leftTableView.currentSelectModel = self.currentSelectModel;
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.seletedIndex inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];//设置选择第一个
        [self.leftTableView reloadData];
    }
}

#pragma mark - rightCollectionView代理点击事件
-(void)classifyPushWithCategotyId:(NSString *)categotyId{
    UIViewController *classifyVC = [[Mediator sharedInstance] classifyWithFilterTerms:@"-1" categotyId:categotyId channelType:@"" orderKey:@"" currentPage:0 keyWord:@"" order:@"" classifyType:@"1"];
    [self.navigationController pushViewController:classifyVC animated:YES];
}

#pragma mark - leftTableView代理点击事件
-(void)BKClassifyLeftTable:(BKClassifyLeftTable *)BKClassifyLeftTable seletedIndex:(NSIndexPath *)indexPath{
    
    [self.upLoadView removeFromSuperview];
    self.seletedIndex = indexPath.section;
    self.currentSelectModel = [self.leftDataArray objectAtIndex:indexPath.section];//更新当前展示数据
    self.leftTableView.currentSelectModel = self.currentSelectModel;
    NSString *key = self.currentSelectModel.name;
    NSArray *thirdModel = [self.classifyDic objectForKey:key];
    [self UpdateRightData:thirdModel];
    BKClasssifyLeftTableViewCell *cell = (BKClasssifyLeftTableViewCell *)[self.leftTableView cellForRowAtIndexPath:indexPath];
    
    [self.leftTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    if (self.leftTableView.index != indexPath.section) {
//        self.leftTableView.view.hidden = NO;
        self.leftTableView.view.backgroundColor = RGBACOLOR(0, 186, 156, 1);
        [UIView animateWithDuration:0.0 animations:^{
            
            self.leftTableView.isFirst = NO;
            [self.leftTableView reloadData];
            self.leftTableView.view.frame = CGRectMake(0, 0, 72, 20);
            self.leftTableView.view.center = cell.center;
            self.leftTableView.view.backgroundColor = RGBACOLOR(0, 186, 156, 0.2);
        } completion:^(BOOL finished) {
//            self.leftTableView.view.backgroundColor = RGBACOLOR(0, 186, 156, 0.1);
            self.leftTableView.view.hidden = YES;
            self.leftTableView.isFirst = YES;
            self.leftTableView.index = indexPath.section;
            [self.leftTableView reloadData];
            
        }];
    }
}

//设置右边的数据
-(void)UpdateRightData:(NSArray*)childrenlist{
    [self.rightdataArray removeAllObjects];
    for (SecondChildrenList *secondModel in childrenlist) {
        if (![secondModel.hasGoodsflag isEqualToString:@"0"]) {
            [self.rightdataArray addObject:secondModel];
            self.rightCollectionView.classifyrightCollArrayView = self.rightdataArray;
        }
    }
    
    if (self.rightdataArray.count == 0) {
        _upLoadView = [[UIView alloc]initWithFrame:CGRectMake(tableWidthSize,0, ScreenWidth-tableWidthSize , ScreenHeight-118)];
        _upLoadView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_upLoadView];
        
        UILabel *label = [[UILabel alloc]init];
        label.text = @"该品类正在备货中";
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        [_upLoadView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(_upLoadView.mas_left).mas_offset(20);
            make.right.mas_equalTo(_upLoadView.mas_right).mas_offset(-20);
            make.centerY.mas_equalTo(_upLoadView.mas_centerY);
        }];
    }
    [self.rightCollectionView scrollRectToVisible:CGRectMake(0, 0, self.rightCollectionView.frame.size.width, self.rightCollectionView.frame.size.height) animated:YES];
    [self.rightCollectionView reloadData];
}

-(NSMutableArray *)leftDataArray{
    if (_leftDataArray == nil) {
        _leftDataArray = [NSMutableArray array];
    }
    return _leftDataArray;
}

-(NSMutableArray *)rightdataArray{
    if (_rightdataArray == nil) {
        _rightdataArray = [NSMutableArray array];
    }
    return _rightdataArray;
}

-(NSMutableArray *)allRightdataArray{
    if (_allRightdataArray == nil) {
        _allRightdataArray = [NSMutableArray array];
    }
    return _allRightdataArray;
}

-(NSMutableDictionary *)classifyDic{
    if (_classifyDic == nil) {
        _classifyDic = [NSMutableDictionary dictionary];
    }
    return _classifyDic;
}

@end
